package com.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.pojo.Category;
import com.ssm.service.CategoryService;
import com.ssm.util.Page;
 


//告诉spring mvc这是一个控制器类
@Controller
public class CategoryController {
	 @Autowired
	 CategoryService categoryService;
	
	  // 类别管理首页
	  @RequestMapping("/")
	  public String index(){
		  return "index";
	  }
	 
	 // 类别列表
	 @RequestMapping("/listCategory")
	 public String listCategory(ModelMap model,Page page){
		 list(model, page);
	     return "listCategory";
	 }
	 
	// 前往添加类别
	@RequestMapping("/addCategory")
	public String add(){
		return "addCategory";
	}
	// 添加类别
	@RequestMapping(value="/addCategory",method=RequestMethod.POST)
	public String add(ModelMap model,Category category) {
		Integer result = categoryService.add(category);
		if (result.equals(1)) return "redirect:listCategory?start="+nowStart(categoryService.total());
	    model.addAttribute("error", "添加");
		return "error";
	}
	// 删除类别
	@RequestMapping("/deleteCategory")
	public String delete(ModelMap model,int id) {
		Integer result = categoryService.delete(id);
		if (result.equals(1)) return "redirect:listCategory?start="+nowStart(id);
	    model.addAttribute("error", "删除");
		return "error";
	}
	// 前往修改类别
	@RequestMapping("/editCategory")
	public String edit(ModelMap model,int id){
		Category category = categoryService.get(id);
	    model.addAttribute("edit", category);
		return "editCategory";
	}
	// 修改类别
	@RequestMapping(value="/editCategory",method=RequestMethod.POST)
	public String edit(ModelMap model,Category category) {
		Integer result = categoryService.update(category);
		if (result.equals(1)) return "redirect:listCategory?start="+nowStart(category.getId());
	    model.addAttribute("error", "修改");
		return "error";
	}

	// 显示列表方法
	private void list(ModelMap model,Page page) {
	     PageHelper.offsetPage(page.getStart(), 5);
	     List<Category> list = categoryService.list();
	     model.addAttribute("list", list);
	     int total = (int) new PageInfo<>(list).getTotal();	     
	     page.caculateLast(total);
	}
	
	// 定位到当前位置方法
	private int nowStart(int nowId) {
	     Page page = new Page();
	     page.caculateLast(nowId);
	     int startId = page.getLast();
		 return startId;	
	}
}